import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

class FileTool{
  //获取本地存取路径的目录
  static Future<String> getStorageDir({required String relativePath}) async{
    Directory fileDr = await getTemporaryDirectory();
    String dirPath = fileDr.path+'/';
    dirPath += relativePath!=null?relativePath:"";
    await Directory(dirPath).create(recursive: true);
    return dirPath;
  }
  static Future<bool> isFileExist(path) async {
    String dirPath = await getStorageDir(relativePath: path);
    File file = File(dirPath+path);
    bool isExist = await file.exists();

    return isExist;
  }

  static String getFileName(String path) {
    var index1 = path.lastIndexOf("/");
    var index2 = path.length;
    var fileName = path.substring(index1 + 1, index2);
    return fileName;
  }

  // 截取文件后缀
  static String getSuffixName(String path) {
    var index1 = path.lastIndexOf(".");
    var index2 = path.length;
    var type = path.substring(index1,index2).toUpperCase();
    return type;
  }

}

class Word {
  final String name;
  final String value;

  Word({required this.name, required this.value});

  // 转换为JSON的方法
  Map<String, dynamic> toJson() => {
    'name': name,
    'value': value,
  };

  // 从CSV行解析数据的工厂构造函数
  factory Word.fromCsvRow(List<String> row) {
    return Word(
      name: row[0],
      value: row[1],
    );
  }
}

Map<String,dynamic> wordMap = {};

// CSV转换为JSON的主函数
Future<void> convertCsvToJson(String csvPath, String jsonPath) async {
  try {
    // 读取CSV文件
    final String content = await rootBundle.loadString(csvPath);
    final List<String> lines = const LineSplitter().convert(content);

    // 解析CSV数据
    final List<Word> words = [];
    for (var line in lines) {
      // 处理CSV行，考虑引号内的逗号
      List<String> row = parseCsvLine(line);

      if (row.length >= 2) {
        words.add(Word.fromCsvRow(row));
      }
    }

    // 转换为JSON格式
    final Map<String, dynamic> jsonMap = {};
    for (var word in words) {
      jsonMap[word.name] = word.value;
    }
    wordMap = jsonMap;
    // 写入JSON文件
    // final jsonString = JsonEncoder.withIndent('  ').convert(jsonMap);
    // 保存到应用程序文档目录
    // final directory = await getApplicationDocumentsDirectory();
    // final file = File('${directory.path}/$jsonPath');
    // await file.writeAsString(jsonString, encoding: utf8);
    print('转换完成: ${wordMap}');
  } catch (e) {
    print('转换失败: $e');
  }
}

// 解析CSV行的辅助函数
List<String> parseCsvLine(String line) {
  List<String> result = [];
  bool inQuotes = false;
  StringBuffer currentField = StringBuffer();

  for (int i = 0; i < line.length; i++) {
    if (line[i] == '"') {
      inQuotes = !inQuotes;
    } else if (line[i] == ',' && !inQuotes) {
      result.add(currentField.toString().trim());
      currentField.clear();
    } else {
      currentField.write(line[i]);
    }
  }

  // 添加最后一个字段
  result.add(currentField.toString().trim());

  // 清理引号
  result = result.map((field) {
    if (field.startsWith('"') && field.endsWith('"')) {
      return field.substring(1, field.length - 1);
    }
    return field;
  }).toList();

  return result;
}
